package com.sensePlusVR.vlcPlayer;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Comparator;
import java.util.Locale;

import org.videolan.libvlc.util.Extensions;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

/**
 * Created by hongbiao on 2015/9/18.
 */
@SuppressLint("DefaultLocale")
public class FileUtil {
    private static final String TAG = FileUtil.class.getName();

    /**
     * save video thumbnail to png file in external storage and return the file uri
     *
     * @param dir
     * @param filename
     * @param bmp
     * @return
     */
	
	public static String saveBitmapFile(String dir, String filename, Bitmap bmp) {
        // check if sdcard exist
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return null;
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
        byte[] bitmapdata = bos.toByteArray();

        //check storage path exist or not
        File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + dir + "/");
        path.mkdirs();
        //create a file to write bitmap data
        File f = new File(path.getAbsolutePath() + "/" + filename + ".png");
        if (f.exists()) {
            f.delete();
        }
        //write the bytes in file
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
            fos.write(bitmapdata);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (f.exists()) {
            return f.getAbsolutePath(); //AndroidUtil.FileToUri(f).toString();
        } else {
            return null;
        }
    }

    public static Bitmap loadBitmapFile(String filePath) {
        if (filePath == null)
            return null;
        Bitmap btp = null;
        try {
            FileInputStream fs = new FileInputStream(filePath);
            BufferedInputStream bs = new BufferedInputStream(fs);
            btp = BitmapFactory.decodeStream(bs);
        } catch (Exception e) {
            Log.e(TAG, "loadBitmapFile failed: " + e);
        }
        return btp;
    }

    public static final FileFilter DEFAULT_FILE_FILTER = new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return pathname.isHidden() == false;
        }
    };

    /**
     * Compares files by name, where directories come always first
     */
    public static class FileNameComparator implements Comparator<File> {
        protected final static int
                FIRST = -1,
                SECOND = 1;

        @Override
        public int compare(File lhs, File rhs) {
            if (lhs.isDirectory() || rhs.isDirectory()) {
                if (lhs.isDirectory() == rhs.isDirectory())
                    return lhs.getName().compareToIgnoreCase(rhs.getName());
                else if (lhs.isDirectory()) return FIRST;
                else return SECOND;
            }
            return lhs.getName().compareToIgnoreCase(rhs.getName());
        }
    }

    /**
     * Compares files by extension.
     * Falls back to sort by name if extensions are the same or one of the objects is a Directory
     *
     * @author Michal
     */
    public static class FileExtensionComparator extends FileNameComparator {
        @Override
        public int compare(File lhs, File rhs) {
            if (lhs.isDirectory() || rhs.isDirectory())
                return super.compare(lhs, rhs);

            String ext1 = getFileExtension(lhs),
                    ext2 = getFileExtension(rhs);

            if (ext1.equals(ext2))
                return super.compare(lhs, rhs);
            else
                return ext1.compareToIgnoreCase(ext2);
        }
    }

    public static class FileSizeComparator extends FileNameComparator {
        private final boolean ascending = false;

        @Override
        public int compare(File lhs, File rhs) {
            if (lhs.isDirectory() || rhs.isDirectory())
                return super.compare(lhs, rhs);

            if (lhs.length() > rhs.length())
                return ascending ? SECOND : FIRST;
            else if (lhs.length() < rhs.length())
                return ascending ? FIRST : SECOND;
            else return super.compare(lhs, rhs);
        }
    }

    public static String getFileNameWithoutExtension(File file)
    {
        String fileName = file.getName().toLowerCase(Locale.ENGLISH);
        int startIndex = 0;
        int endIndex = fileName.lastIndexOf(".");
        if (endIndex == -1) {
            endIndex = fileName.length()-1;
        }
        startIndex = fileName.lastIndexOf(".", endIndex-1);
        if(startIndex<0)
            startIndex = 0;
        return fileName.substring(startIndex ,endIndex);
    }
    public static String getFileExtensionWithDot(File file)
    {
        String fileName = file.getName().toLowerCase(Locale.ENGLISH);
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex != -1) {
            return fileName.substring(dotIndex);
        }else {
            return "";
        }
    }
    public static String getFileExtension(File file) {
        return getFileExtension(file.getName());
    }

    /**
     * Gets extension of the file name excluding the . character
     */
    public static String getFileExtensionWithDot(String fileName) {
        if (fileName.contains("."))
            return fileName.substring(fileName.lastIndexOf('.'));
        else
            return "";
    }
    /**
     * Gets extension of the file name excluding the . character
     */
    public static String getFileExtension(String fileName) {
        if (fileName.contains("."))
            return fileName.substring(fileName.lastIndexOf('.') + 1);
        else
            return "";
    }

    public static boolean directoryContainsVideoFiles(File dir) {
        if (!dir.isDirectory() || dir.isHidden()) return false;
        try {
            File[] files = dir.listFiles();
            for (File f : files) {
                if (!f.isHidden()) {
                    if (f.isDirectory()) {
                        if (!directoryEmpty(f)) { //directoryContainsVideoFiles
                            return true;
                        }
                    } else {
                        String fileExt = getFileExtension(f).toLowerCase();
                        if (/*Extensions.AUDIO.contains(fileExt) ||*/
                                Extensions.VIDEO.contains(fileExt) /*||
                               Extensions.PLAYLIST.contains(fileExt)*/) {
                            return true;
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return false;
    }

    public static boolean directoryEmpty(File dir) {
        if (!dir.isDirectory() || dir.isHidden()) return false;
        try {
            File[] files = dir.listFiles();
            if (files == null || files.length == 0) return true;
            for (File f : files) {
                if (!f.isHidden()) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "directoryEmpty : "+dir+", Exception: "+e);
        }
        return false;
    }
}
